<?php

namespace app\courier\controller;

use app\model\CourierInfo as ModelCourierInfo;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\UserOrder as ModelUserOrder;
use app\model\UserOrderLog as ModelUserOrderLog;
use app\model\StationInfo as ModelStationInfo;
use app\model\ItemType as ModelItemType;
use app\model\Package as ModelPackage;
use app\model\SysSetting as ModelSysSetting;
use app\model\CashStream as ModelCashStream;
use think\Db;


class Order extends Member
{

    /*
     * 修改上班状态
     * URI：/courier/duty.set
     */
    public function courierSetDuty()
    {
        $str_is_on_duty = $this->_getContentParams('state');
//        $is_on_duty = 'off';
        $duty = ModelCourierInfo::getInstance()->toValue(['id'=>$this->courier_id],'is_on_duty');
//        echo Db::name('')->getLastSql();
        if ($duty == 'on') _returnData(15023);
        $where_arr = [
            'id' => $this->courier_id,
        ];
        $up_arr = [
            'is_on_duty' => $str_is_on_duty
        ];
        $res = ModelCourierInfo::getInstance()->toUpdate($where_arr,$up_arr);
        if ($res) _returnData();
    }

    /*
     * 待抢订单
     * URI：/courier/order.grab
     * type 1:收件单；2：派件单
     */
    public function toGrabTheOrder()
    {
        $page = $this->_getContentParams('page');
        _toValidate('id',$page,10005);
        if (!$page) $page = 1;
        $type = $this->_getContentParams('type');
//        $type =1;

        $listRow = 20;
        //获取快递员经纬度
        $lat = $this->_getContentParams('lat');
        $lng = $this->_getContentParams('lng');
        if (empty($lat) || empty($lng)){
            _returnError(15018);
        }
        $courierAreaId = ModelCourierInfo::getInstance()->toFind(['id'=>$this->courier_id],'area_id,delivery_area_id');//获取快递员服务范围
        $sendId = $courierAreaId['area_id'];//期望收件服务地区
        $deliveryId = $courierAreaId['delivery_area_id'];//期望派件服务地区
        //获取订单数据
        $orderData = ModelUserOrder::getInstance()->toGrabTheOrder($sendId,$deliveryId,$type);
        $listCount = $orderData['listCount']; //总条数
        $totalPage = ceil($listCount/$listRow);
        $firstRow = ($page - 1)*$listRow;
        $orderList = $orderData['list'];//订单列表
//        echo count($orderList);
        if (count($orderList) != 0 ){
            //获取距离
            foreach ($orderList as $key=>&$value){
                $value['distance'] = $this->getDistance($lat,$lng,$value['sendLat'],$value['sendLng']);
                unset($value['sendLat']);
                unset($value['sendLng']);
            }
            $newOrderList = my_sort($orderList,'distance');//按距离排序
            foreach ($newOrderList as &$v)
            {
                if ($v['distance'] <= 1000){
                    $v['distance'] = $v['distance'].'m';
                }else{
                    $v['distance'] = sprintf('%.1f', $v['distance']/1000).'km';
                }
            }
            $data['totalPages'] = $totalPage;
            $data['orderList'] = $this->getArray($newOrderList,$firstRow,$listRow);
        }else{
            $data['totalPages'] = 0;
            $data['orderList'] = [];
        }
        //判断用户是否已经实名认证或者入驻
        $bool_res  = ModelCourierInfo::getInstance()->checkIsAuth($this->courier_id);
        if ($bool_res){
            _returnData($data);
        }else{
            _returnData();
        }

    }

    /*
     * 抢单/入库
     * URI：/courier/order.get
     * type:1:抢单；2：入库
     */
    public function getOrder()
    {
        $orderId = $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10005);
        $type = $this->_getContentParams('type');

//        $orderId = 87;
//        $type = 1;
        $orderInfo = ModelUserOrder::getInstance()->toFind(['order_id'=>$orderId],'order_state,order_sn');
        if (!$orderInfo) _returnError(14012);//验证订单是否存在
        _toCompare(in_array($orderInfo['order_state'],['10','60']),'!=',true,15014);//手慢了，该订单已经被抢了
        //生成取件码
        $pickCode = getCode();
        //订单添加到快递员订单表
        $data['order_id'] = $orderId;
        $data['courier_id'] = $this->courier_id;
        $data['pick_code'] = $pickCode;
        $data['is_pick'] = $type;
        $add_res = ModelCourierOrder::getInstance()->toAdd($data);
        if (!$add_res) _returnError(10010);
        //修改订单状态为20：未支付，已接单
        $where_arr = [
            'order_id' => $orderId,
        ];
        switch ($type){
            case 1 :
                $up_arr = [
                    'order_state' => '20',
                    'pick_code' => $pickCode,
                ];
                break;
            case 2 :
                $up_arr = [
                    'order_state' => '70',
                    'pick_code' => $pickCode,
                ];
                break;
            default:
                _returnError(10014);
                break;
        }

        $up_res = ModelUserOrder::getInstance()->toUpdate($where_arr,$up_arr);
        if(!$up_res)  _returnError(15015);
        //写入订单日志
        $add_res = ModelUserOrderLog::getInstance()->addOrderLog($orderId,'1',$this->courier_id);
//        echo $add_res;
//        echo Db::name('')->getLastSql();die;
        _toCompare(($add_res > 0) ,'==',false,10010);
        _returnData();


    }
    /*
     * 验证取件码(用户端 or 站点)
     * URL：/courier/parcel.pickup
     */
    public function pickUpParcel()
    {
        $pickCode = $this->_getContentParams('pickCode');
        _toCompare(empty($pickCode),'==',true,15032);
//        $pickCode = 1234;
        $courierOrderInfo = ModelCourierOrder::getInstance()->toFind(['courier_id'=>$this->courier_id,'pick_code'=>$pickCode],'id,order_id');

        if (!$courierOrderInfo) {
            _returnError(14012);
        }else{
            //订单存在，修改取件码使用状态
            $bool_res = ModelCourierOrder::getInstance()->toUpdate(['id'=>$courierOrderInfo['id']],['is_use'=>1]);
            if (!$bool_res) _returnError(10011);
            _returnData(['orderId'=>$courierOrderInfo['order_id']]);

        }
    }
    /*
     * 确认寄件信息
     * URI：/courier.order.confirm
     */
    public function confirmOrderInfo()
    {
        $orderId = $this->_getContentParams('orderId');
        //收件人信息
        $data['recipient_info'] = $this->_getContentParams('recipientInfo');
        _toCompare(empty($data['recipient_info']),'===',true,14015);
        //收件人经度
        $data['received_lng'] = $this->_getContentParams('receivedLng');
        _toCompare(empty($data['received_lng']),'===',true,15036);
        //收件人纬度
        $data['received_lat'] = $this->_getContentParams('receivedLat');
        _toCompare(empty($data['received_lat']),'===',true,15037);
        //重量
        $data['item_weight'] = $this->_getContentParams('weight');
        _toCompare($data['item_weight'],'<=',0,14002);
//        _toValidate('math', $data['item_weight'], 14002);
        //类型
        $data['item_type'] = ModelItemType::getInstance()->getItemName($this->_getContentParams('itemTypeId'));
        _toCompare(empty($data['item_type']), '==', true, 14003);
        //声明价值
        $data['item_price'] = $this->_getContentParams('itemPrice');
        if ($data['item_price'] > 0) {
            _toValidate('money', $data['item_price'], 14004);
        }
        //保价
        $data['protect_price'] = $this->_getContentParams('protectPrice');
        if ($data['protect_price'] > 0) {
            _toValidate('money', $data['protect_price'], 14005);
        }
        //合计运费
        $data['order_amount'] = $this->_getContentParams('orderAmount');
        _toValidate('money', $data['order_amount'], 14018);
        //基础运费
        $data['first_heavy_fee'] = $this->_getContentParams('firstFee');
        _toValidate('money', $data['order_amount'], 14016);
        //续重费
        $data['other_heavy_fee'] = $this->_getContentParams('otherFee');
        _toValidate('money', $data['order_amount'], 14017);
        //运单号
        $data['express_order_sn'] = $this->_getContentParams('expressSn');
        //物流公司id/名称
        $data['express_id'] = $this->_getContentParams('expressId');
        $data['express_name'] = $this->_getContentParams('expressName');
        _toCompare(($data['express_id']>0),'==',false,15010);
        $data['order_state'] = 25;
        //修改订单表状态
        $userOrderRes = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],$data);
        //修改快递员订单表状态
        $nowOrderState = ModelUserOrder::getInstance()->toValue(['order_id'=>$orderId],'order_state');
        $courierOrderStateRes = ModelCourierOrder::getInstance()->toUpdate(['order_id'=>$orderId,'courier_id'=>$this->courier_id],['state'=>$nowOrderState]);
        if ($userOrderRes && $courierOrderStateRes){
            //写入订单记录
            $logRes = ModelUserOrderLog::getInstance()->addOrderLog($orderId,1,$this->courier_id);
            if ($logRes) _returnData();
        }
        _returnError(10011);

    }
    /*
     * 确认到达目的地
     * URI：/courier/confirm.arrive
     */
    public function confirmArrive()
    {
        $orderId = $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $updateRes = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],['arrive_time'=>$this->_now]);
        if ($updateRes) _returnData();
        _returnError(10011);
    }


    /*
     * 我的订单
     * URI：/courier/myOrder.list
     * type:1:未取件；2：已取件；3待配送
     */
    public function myOrderList()
    {
        $type = $this->_getContentParams('type');

        //获取快递员经纬度
        $lat = $this->_getContentParams('lat');
        $lng = $this->_getContentParams('lng');
        if (empty($lat) || empty($lng)){
            _returnError(15018);
        }
        $data = ModelUserOrder::getInstance()->myOrder($this->courier_id,$type);

        if ($data){
            if ($type == 1 || $type ==3){
                //获取距离
                foreach ($data as $key=>&$value){
                    $value['distance'] = $this->getDistance($lat,$lng,$value['lat'],$value['lng']);
//                unset($value['lat']);
//                unset($value['lng']);
                }

                $newData = my_sort($data,'distance');//按距离排序
                foreach ($newData as &$v)
                {
                    if ($v['distance'] <= 1000){
                        $v['distance'] = $v['distance'].'m';
                    }else{
                        $v['distance'] = sprintf('%.1f', $v['distance']/1000).'km';
                    }
                }
                _returnData(['orderlist'=>$newData]);
            }elseif ($type == 2){
                _returnData(['orderlist'=>$data]);

            }
        }else{
            _returnData(['orderlist'=>[]]);

        }

    }

    /*
     * 附近网点
     * /courier/station.nearby
     */
    public function nearbyStation()
    {
//        $courierAreaId = ModelCourierInfo::getInstance()->toValue(['id'=>$this->courier_id],'area_id');
        $field = 'id,name,address,lng,lat';
        $stationList = ModelStationInfo::getInstance()->toSelect([],$field);
        //获取快递员经纬度
        $position = action('communal/common/getPosition');
        //获取距离
        foreach ($stationList as $key=>&$value){
            $value['distance'] = $this->getDistance($position['lat'],$position['lng'],$value['lat'],$value['lng']);
        }

        $newStationList = my_sort($stationList,'distance');//按距离排序
        foreach ($newStationList as &$v)
        {
            if ($v['distance'] <= 1000){
                $v['distance'] = $v['distance'].'m';
            }else{
                $v['distance'] = sprintf('%.1f', $v['distance']/1000).'km';
            }
        }
        _returnData(['stationList'=>$newStationList]);
    }

    /*
     * 订单详情
     * URI：/courier/order.details
     */
    public function orderDetails()
    {
       $orderId= $this->_getContentParams('orderId');
       _toValidate('id',$orderId,10009);
//        $orderId = 12;
       $orderInfo = ModelUserOrder::getInstance()->orderDetail($orderId,$this->courier_id);
       if ($orderInfo){
           $orderInfo['totalFreightFee']  =  sprintf("%.2f",$orderInfo['firstFee'] + $orderInfo['otherFee']);
           _returnData(['orderDetails'=> $orderInfo]);

       }
       _returnError(12001);
    }

    /*
     * 快递员取消配送
     * URI：/courier.order.clear
     */
    public function courierOrderClear()
    {
        $orderId = $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $clearReason = $this->_getContentParams('reason');
        _toCompare(empty($clearReason),'==',true,15026);

        $where = [
            'order_id' => $orderId,
        ];
        $update = [
            'order_state' => 90,
            'clear_type' => 2,
            'clear_reason' => $clearReason,
        ];
        //修改订单表状态并写入原因
        $upRes = ModelUserOrder::getInstance()->toUpdate($where,$update);
        if (!$upRes) _returnError(10011);
        //写入订单日志表
        $addRes = ModelUserOrderLog::getInstance()->addOrderLog($orderId,1,$this->courier_id,$clearReason);

        if ($addRes) _returnData();
        _returnError(10011);

    }

    /*
     * 确认签收
     * URI：/courier/order.confirm
     */
    public function orderConfirm()
    {
        $orderId = $this->_getContentParams('orderId');
        _toValidate('id',$orderId,10009);
        $imgUrl =  $this->_getContentParams('imgUrl');
        _toCompare(empty($imgUrl),'==',true,15027);
        //获取订单号
        $orderInfo = ModelUserOrder::getInstance()->toFind(['order_id'=>$orderId],'order_sn,order_amount');
//        //获取快递员分佣类型
//        $commissionType = ModelCourierInfo::getInstance()->toValue(['id'=>$this->courier_id],'commission_type');
//        if ($commissionType == 1){
//            $commission = ModelSysSetting::getInstance()->courierCharges($commissionType);
//        }elseif($commissionType == 2){
//            $commission = ModelSysSetting::getInstance()->courierCharges($commissionType)*$orderInfo['order_amount']/100;
//        }else{
//            _returnError(15034);
//        }

         //添加快递员分佣
        $commission = ModelCourierInfo::getInstance()->getCommission($this->courier_id,$orderId);
        //修改账户余额
        $editBalance = ModelCashStream::getInstance()->editBalance(1,$this->courier_id,0,$commission,'订单配送完成--分佣',$orderInfo['order_sn'],$orderId);

        if ($editBalance)
        {
            //修改订单表状态
            $upRes = ModelUserOrder::getInstance()->toUpdate(['order_id'=>$orderId],['order_state'=>80]);
            if (!$upRes) _returnError(10011);
            //写入订单日志表
            $addRes = ModelUserOrderLog::getInstance()->addOrderLog($orderId,1,$this->courier_id,$imgUrl);
            if ($addRes) _returnData();
            _returnError(10011);
        }else{
            _returnError(15035);
        }
    }

    /*
     * 订单记录
     * URI：/courier/order.record
     */
    public function orderRecord()
    {
        $page = $this->_getContentParams('page');
        _toValidate('id',$page,10005);
//        $page = 1;
        $listRow = 20;
        $firstRow = ($page - 1)*$listRow;

        $list = ModelUserOrder::getInstance()->orderRecord($this->courier_id,$firstRow,$listRow);
        _returnData($list);
    }

}

